package com.itheima.blog.gateway.admin.filter;

import com.alibaba.nacos.api.utils.StringUtils;
import com.alibaba.nacos.common.utils.ExceptionUtil;
import com.itheima.blog.util.JwtUtils;
import com.itheima.blog.util.Payload;
import com.itheima.blog.util.constants.Constants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;


@Slf4j
@Component
public class AuthFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        // 根据url判断是否是登录请求
        String path = request.getURI().getPath();
        if(path.indexOf("/login/in") >= 0){
            // 是登陆，直接放行
           return chain.filter(exchange);
        }
        // 否，校验token
        // 从请求头中读取token
        String token = request.getHeaders().getFirst(Constants.HEADER_TOKEN_ADMIN);
        // 判断token是否为空
        if(StringUtils.isEmpty(token)){
            // token为空，401
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        // token不是空，校验token合法
        try{
            Payload payload = JwtUtils.getInfoFromToken(token);
            Integer userId = payload.getUserId();
            if(userId == null || userId <= 0){
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                return response.setComplete();
            }
            // 把userId继续向下游的微服务进行传递
            request.mutate().header(Constants.HEADER_USER_ID_ADMIN, ""+userId);
        }catch(Exception e){
            log.error("token={}, token解析异常:{}", token, ExceptionUtil.getStackTrace(e));
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        // 通过，放行
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
